﻿using AutoMapper;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using WMS.FC.Domain.DomainObject.System;
using WMS.FC.Domain.Repository;
using WMS.FC.Domain.Service.System.Interface;

namespace WMS.FC.Domain.Service.System
{
    public class OperateDataService : ServiceBase, IOperateDataService
    {
        protected readonly ISystemRepository systemRepository;
        protected readonly IMenuRepository menuRepository;

        public OperateDataService(ILogger<ServiceBase> logger, IOptions<WmsSettings> options, IMapper mapper, ISystemRepository systemRepository, IMenuRepository menuRepository) : base(logger, options, mapper)
        {
            this.systemRepository = systemRepository;
            this.menuRepository = menuRepository;
        }

        public async Task<ActionResultBase> OperateData(string menuId, List<string> selectedIds, UserInfo userInfo)
        {
            var result = new ActionResultBase("操作数据");
            try
            {
                if (string.IsNullOrWhiteSpace(menuId))
                    return result.ArgumentError("菜单ID不能为空");

                if (selectedIds.Count == 0 || selectedIds.Any(id => string.IsNullOrWhiteSpace(id)))
                    return result.ArgumentError("选择编辑数据ID不能为空");

                var menuPO = await menuRepository.GetMenu(Convert.ToInt64(menuId));
                if (menuPO == null)
                    return result.DbError($"ID:{menuId},菜单数据未找到");

                if (string.IsNullOrWhiteSpace(menuPO.Sql))
                    return result.BusinessError($"菜单:{menuPO.NameCN},sql语句为空");

                var parameters = new Dictionary<string, object>
                {
                    { "id", $"{string.Join("','", selectedIds)}" }
                };
                var sqlList = menuPO.Sql.Split(";", StringSplitOptions.RemoveEmptyEntries & StringSplitOptions.TrimEntries);
                var count = 0;
                foreach (var sql in sqlList)
                {
                    count += await systemRepository.ExecuteNoQuery(menuPO.Sql, userInfo, parameters);
                }

                if (count == 0)
                    return result.DbError("操作数据0条");

                result.Message = "操作数据成功";
            }
            catch (Exception ex)
            {
                return result.Exception(ex);
            }

            return result;
        }
    }
}
